<template>
  <div style="font-size: 14px">
    <!-- 添加变更弹窗 -->
    <el-drawer
      v-model="dialogVisible"
      :title="props.type == 'upgrade' ? '请求升级为变更' : details.eno ? '变更编辑' : '变更新增'"
      direction="rtl"
      size="1000"
    >
      <el-form ref="addForm" v-if="dialogVisible" :model="form" :rules="rules" label-width="120" v-loading="loading">
        <el-row v-if="!details.eno">
          <el-col :span="12">
            <el-form-item label="变更模板">
              <el-select v-model="templateJson" placeholder="请选择变更模板" @change="tempChagne">
                <el-option
                  v-for="item in tempList"
                  :key="item.templateId"
                  :label="item.templateName"
                  :value="item.templateJson"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="变更标题" prop="etitle">
          <el-input v-model="form.etitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="描述" required>
          <WangEditor v-model:value="form.edesc" height="200px" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属客户" prop="companyNo">
              <el-select v-model="form.companyNo" :disabled="props.type == 'upgrade'" placeholder="请选择所属客户">
                <el-option v-for="item in orgList" :key="item.orgNo" :label="item.orgName" :value="item.orgNo" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="变更分类" prop="categoryNo">
              <el-tree-select
                v-model="form.categoryNo"
                lazy
                :load="cateTreeLoad"
                :cache-data="cacheCateData"
                check-strictly
                :render-after-expand="false"
                placeholder="请选择变更分类"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开始时间" prop="planStartTime">
              <el-date-picker
                v-model="form.planStartTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束时间" prop="planEndTime">
              <el-date-picker
                v-model="form.planEndTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select v-model="form.priorityNo" placeholder="请选择优先级">
                <el-option v-for="item in priorityList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="影响">
              <el-select v-model="form.effectRangeNo" placeholder="请选择影响">
                <el-option v-for="item in effectRangeList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急度">
              <el-select v-model="form.seriousnessNo" placeholder="请选择紧急度">
                <el-option v-for="item in seriousnessList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="指派组">
              <!-- <el-cascader v-model="form.orgNo" :options="groupList" :show-all-levels="false" style="width: 100%" /> -->
              <el-input
                style="flex: 1; overflow: hidden"
                v-model="assigneeGroupName"
                placeholder="请选择指派组"
                :readonly="true"
                clearable
              ></el-input>
              <el-button
                style="margin-left: 10px"
                type="primary"
                :icon="Search"
                @click="selectDepartment('filterForm.assigneeGroupNo', '请选择指派组')"
              ></el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="指派技术员">
              <div style="display: flex; width: 100%">
                <el-input
                  style="flex: 1; overflow: hidden"
                  v-model="form.technicianName"
                  placeholder="请选择技术员"
                  :readonly="true"
                ></el-input>
                <el-button
                  style="margin-left: 10px"
                  type="primary"
                  :icon="Search"
                  @click="selectUser('technicianNo')"
                ></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-tabs v-model="tabName" class="demo-tabs">
              <el-tab-pane label="拓展信息" name="one">
                <div v-for="(item, index) in attrVals" :key="index">
                  <div style="margin-bottom: 8px; font-weight: bold">{{ item.attrGroupName }}</div>
                  <div class="table-data-box">
                    <div class="data-cell row" v-for="(vo, idx) in item.children" :key="idx">
                      <div class="label w-170">{{ vo.attrAsName }}</div>
                      <div class="content">
                        <!-- 文本 -->
                        <el-input v-if="vo.attrType == 'String'" v-model="vo.value" />
                        <!-- 时间 -->
                        <el-date-picker
                          v-if="vo.attrType == 'Date'"
                          v-model="vo.value"
                          type="datetime"
                          placeholder="请选择时间"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          style="width: 100%"
                        />
                        <template v-if="vo.attrType == 'DataDictionaray'">
                          <!-- 选择优先级 -->
                          <el-select v-if="vo.attrdataDictionary == 'priority'" v-model="vo.value" placeholder="请选择优先级">
                            <el-option v-for="v in priorityList" :key="v.dcode" :label="v.dname" :value="v.dcode" />
                          </el-select>
                          <!-- 选择影响范围 -->
                          <el-select
                            v-if="vo.attrdataDictionary == 'effectRange'"
                            v-model="vo.value"
                            placeholder="请选择影响范围"
                          >
                            <el-option v-for="v in effectRangeList" :key="v.dcode" :label="v.dname" :value="v.dcode" />
                          </el-select>
                          <!-- 选择紧急度 -->
                          <el-select v-if="vo.attrdataDictionary == 'seriousness'" v-model="vo.value" placeholder="请选择紧急度">
                            <el-option v-for="v in seriousnessList" :key="v.dcode" :label="v.dname" :value="v.dcode" />
                          </el-select>
                        </template>
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="attrVals.length == 0" style="color: #999999">暂无拓展数据</div>
              </el-tab-pane>
              <el-tab-pane label="附件" name="two">
                <el-upload ref="uploadRef" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadChange">
                  <template #trigger>
                    <el-button type="primary" plain>添加附件</el-button>
                  </template>
                  <!-- <template #tip>
                    <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
                  </template> -->
                </el-upload>
                <el-table :data="enclosureList" border style="margin-top: 10px">
                  <el-table-column label="名称" prop="attachmentName"></el-table-column>
                  <el-table-column label="服务器路径" prop="url"></el-table-column>
                  <el-table-column label="操作" align="center" width="180">
                    <template #default="scope">
                      <el-button @click="delFile(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="变更计划" name="three">
                <el-form-item label="" label-width="80">
                  <el-radio-group v-model="changePlanType" aria-label="label position">
                    <el-radio-button value="effect">影响</el-radio-button>
                    <el-radio-button value="onLinePlan">上线计划</el-radio-button>
                    <el-radio-button value="returnPlan">回退计划</el-radio-button>
                    <el-radio-button value="checklist">测试计划</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="影响描述" label-width="80" v-if="changePlanType == 'effect'">
                  <el-input type="textarea" v-model="form.effect" :rows="3" placeholder="请输入影响描述"></el-input>
                </el-form-item>
                <el-form-item label="上线计划" label-width="80" v-if="changePlanType == 'onLinePlan'">
                  <el-input type="textarea" v-model="form.onLinePlan" :rows="3" placeholder="请输入上线计划"></el-input>
                </el-form-item>
                <el-form-item label="回退计划" label-width="80" v-if="changePlanType == 'returnPlan'">
                  <el-input type="textarea" v-model="form.returnPlan" :rows="3" placeholder="请输入回退计划"></el-input>
                </el-form-item>
                <el-form-item label="测试计划" label-width="80" v-if="changePlanType == 'checklist'">
                  <el-input type="textarea" v-model="form.checklist" :rows="3" placeholder="请输入测试计划"></el-input>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="关联配置项" name="four">
                <div style="margin-bottom: 10px">
                  <el-button type="primary" @click="showSelectAssetMask">添加配置项</el-button>
                </div>
                <el-table border :data="assetList" max-height="400px">
                  <el-table-column label="固定资产编号" prop="cino"></el-table-column>
                  <el-table-column label="名称" prop="ciname"></el-table-column>
                  <el-table-column label="分类" prop="categoryName"></el-table-column>
                  <el-table-column label="状态" prop="status"></el-table-column>
                  <el-table-column label="操作" width="150" align="center">
                    <template #default="scope">
                      <el-button @click="delAsset(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="关联服务" name="five">
                <div style="margin-bottom: 10px">
                  <el-button type="primary" @click="showSelectServesMask">添加服务</el-button>
                </div>
                <el-table border :data="serviceDirectoryList" max-height="400px">
                  <el-table-column type="index" label="序号" width="120" align="center"></el-table-column>
                  <el-table-column label="服务名称" prop="cname"></el-table-column>
                  <el-table-column label="操作" width="150" align="center">
                    <template #default="scope">
                      <el-button @click="delServe(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-drawer>
    <!-- 选择用户弹窗 -->
    <SelectUserMask v-if="dialogVisible" ref="selectUserMask" @change="userChange"></SelectUserMask>
    <!-- 选择服务 -->
    <SelectServesMask v-if="dialogVisible" ref="selectServesMask" @change="serveChange"></SelectServesMask>
    <!-- 选择配置项（资产） -->
    <SelectAssetMask v-if="dialogVisible" ref="selectAssetMask" @change="assetChange"></SelectAssetMask>
    <!-- 选择部门 -->
    <SelectDepartment ref="selectDepartmentMask" :title="selectDepartmentTitle" @change="departmentChange"></SelectDepartment>
  </div>
</template>

<script setup lang="ts" name="AddChangeMask">
import { ref, reactive, computed, watch, onMounted } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import {
  findByTemplateType,
  changeInfo,
  statCiChangeConflict,
  saveChange,
  changeEdit,
  getCategoryTree
} from "@/api/modules/changeManagement";
import { findAllEventAttachment, uploadAttr, attributeList } from "@/api/modules/common";
import { useUserStore } from "@/stores/modules/user";
import { useAllChangeOptions } from "@/stores/modules/change";
import SelectUserMask from "@/components/SelectUserMask/index.vue";
import SelectServesMask from "@/components/SelectServesMask/index.vue";
import SelectAssetMask from "@/components/SelectAssetMask/index.vue";
import SelectDepartment from "@/components/SelectDepartment/SelectDepartment.vue";
const userStore = useUserStore();
const allChangeOptions = useAllChangeOptions();

const props = defineProps({
  type: {
    type: String,
    default: ""
  }
});

const details = ref<any>({});

interface OrgItem {
  orgNo: string;
  orgName: string;
}

// 所属客户列表
const orgList = computed(() => {
  let list = ref<OrgItem[]>(allChangeOptions.orgList || []);
  let companyNo = userStore.userInfo.companyNo;
  let hasItem = false;
  list.value.forEach((item: any) => {
    if (item.orgNo === companyNo) {
      hasItem = true;
    }
  });
  if (!hasItem) {
    list.value.push({
      orgName: userStore.userInfo.companyName,
      orgNo: userStore.userInfo.companyNo
    });
  }
  return list.value;
});

interface UniversalItem {
  id: number | string;
  eavId: number;
  label: string;
  cname: string;
  dname: string;
  dcode: string;
}

// 分类列表
const cateList = computed<any[]>(() => {
  let list = JSON.parse(JSON.stringify(allChangeOptions.cateList));
  list.forEach((item: any) => {
    item.label = item.cname;
    item.value = item.id;
    if (item.children && item.children.length > 0) {
      item.children.forEach((vo: any) => {
        vo.label = vo.cname;
        vo.value = vo.id;
      });
    }
  });
  return list;
});

// 查询分类树
const cateTreeLoad = (node, resolve) => {
  if (node.level == 0) {
    resolve(cateList.value);
  } else {
    // 获取分类列表
    getCategoryTree({
      types: "Change",
      parentEventId: node.data.value
    }).then((res: any) => {
      res.forEach(item => {
        item.label = item.attr.cname;
        item.value = item.attr.id;
      });
      resolve(res);
    });
  }
};

// 优先级列表
const priorityList = computed<UniversalItem[]>(() => {
  return allChangeOptions.priorityList;
});

// 影响列表
const effectRangeList = computed<UniversalItem[]>(() => {
  return allChangeOptions.effectRangeList;
});

// 紧急度列表
const seriousnessList = computed<UniversalItem[]>(() => {
  return allChangeOptions.seriousnessList;
});

// 指派组
// const groupList = computed(() => {
//   let list = JSON.parse(JSON.stringify(allChangeOptions.groupList));
//   list.forEach((item: { label: any; orgName: any; value: any; orgNo: any; children: any[] }) => {
//     item.label = item.orgName;
//     item.value = item.orgNo;
//     if (item.children) {
//       item.children.forEach((vo: { label: any; orgName: any; value: any; orgNo: any; children: any[] }) => {
//         vo.label = vo.orgName;
//         vo.value = vo.orgNo;
//         if (vo.children) {
//           vo.children.forEach((v: { label: any; orgName: any; value: any; orgNo: any }) => {
//             v.label = v.orgName;
//             v.value = v.orgNo;
//           });
//         }
//       });
//     }
//   });
//   return list;
// });

const form = reactive({
  etitle: "", // 标题
  edesc: "", // 内容
  companyNo: "", // 所属客户
  companyName: "", // 所属客户
  categoryNo: "", // 分类
  categoryName: "", // 分类
  planStartTime: "", // 计划开始时间
  planEndTime: "", // 计划结束时间
  priorityNo: "",
  effectRangeNo: "",
  seriousnessNo: "",
  orgNo: "",
  technicianNo: "", // 技术员
  technicianName: "", // 技术员
  attachmentStr: "", // 附件
  effect: "", // 影响
  onLinePlan: "", // 上线计划
  returnPlan: "", // 回退计划
  checklist: "" // 测试计划
});
// 选择部门
const selectDepartmentType = ref("");
const selectDepartmentTitle = ref("");
const selectDepartmentMask = ref();
const assigneeGroupName = ref("");
const selectDepartment = (type: string, title: string) => {
  selectDepartmentType.value = type;
  selectDepartmentTitle.value = title;
  selectDepartmentMask.value?.open();
};
const departmentChange = e => {
  switch (selectDepartmentType.value) {
    // case "filterForm.requestorOrgNo":
    //   requestorOrgName.value = e.orgName;
    //   filterForm.requestorOrgNo = e.orgNo;
    //   break;
    case "filterForm.assigneeGroupNo":
      form.orgNo = e.orgNo;
      assigneeGroupName.value = e.orgName;
      break;
    // case "conditionForm.propValue":
    //   conditionForm.propDisplayValue = e.orgName;
    //   conditionForm.propValue = e.orgNo;
    //   break;
    default:
      break;
  }
};

const rules = reactive({
  etitle: [{ required: true, message: "请输入变更标题", trigger: "blur" }],
  companyNo: [{ required: true, message: "请选择所属客户", trigger: "change" }],
  categoryNo: [{ required: true, message: "请选择变更分类", trigger: "change" }],
  planStartTime: [{ required: true, message: "请选择计划开始时间", trigger: "change" }],
  planEndTime: [{ required: true, message: "请选择计划结束时间", trigger: "change" }]
});

// 模板列表
const templateJson = ref("");
const tempList = ref<any[]>([]);
// 选择模板
const tempChagne = e => {
  if (e) {
    let data = JSON.parse(e);
    // console.log(data);
    form.etitle = data.etitle;
    form.edesc = data.edesc;
    form.companyNo = data.companyNo;
    form.companyName = data.companyName;
    form.categoryNo = data.categoryNo;
    form.categoryName = data.categoryName;

    form.planStartTime = data.planStartTime.replace(/T/g, " ");
    form.planEndTime = data.planEndTime.replace(/T/g, " ");

    form.priorityNo = data.priorityNo;
    form.effectRangeNo = data.effectRangeNo;
    form.seriousnessNo = data.seriousnessNo;
    form.orgNo = data.orgNo;
    form.technicianNo = data.technicianNo;
    form.technicianName = data.technicianName;
    form.attachmentStr = data.attachmentStr;
    form.effect = data.effect;
    form.onLinePlan = data.onLinePlan;
    form.returnPlan = data.returnPlan;
    form.checklist = data.checklist;

    // 附件
    enclosureList.value = [];
    let imgs = data.attachmentStr.split("-s-").filter(item => {
      return item.length > 0;
    });
    if (imgs.length > 0) {
      imgs.forEach(item => {
        let arr = item.split("==");
        enclosureList.value.push({
          attachmentName: arr[0],
          url: arr[1],
          size: arr[2]
        });
      });
    }

    // 服务
    serviceDirectoryList.value = [];
    if (data.serviceNos) {
      for (const key in data.serviceNos) {
        serviceDirectoryList.value.push({
          id: key,
          cname: data.serviceNos[key]
        });
      }
    }
  }
};

// 监听所属客户
watch(
  () => form.companyNo,
  val => {
    if (val) {
      orgList.value.forEach(item => {
        if (item.orgNo == val) {
          form.companyName = item.orgName;
        }
      });
    } else {
      form.companyName = "";
    }
  }
);

// 拓展信息列表
const attrVals = ref<any>([]);

// 监听变更分类
watch(
  () => form.categoryNo,
  val => {
    form.companyName = "";
    attrVals.value = [];
    if (val) {
      cateList.value.forEach(item => {
        if (item.id == val) {
          form.companyName = item.cname;
          if (item.eavId) {
            attributeList({
              eavNo: item.eavId
            }).then((res: any) => {
              let list = res || [];
              let arr = ref<any[]>([]);
              list.forEach(item => {
                item.value = "";
                if (arr.value.length == 0) {
                  arr.value.push({
                    attrGroupName: item.attrGroupName,
                    children: [item]
                  });
                } else {
                  let hasAttrGroupName = false;
                  arr.value.forEach(vo => {
                    if (vo.attrGroupName == item.attrGroupName) {
                      hasAttrGroupName = true;
                      vo.children.push(item);
                    }
                  });
                  if (!hasAttrGroupName) {
                    arr.value.push({
                      attrGroupName: item.attrGroupName,
                      children: [item]
                    });
                  }
                }
              });
              attrVals.value = arr.value;
            });
          }
        }
      });
    }
  }
);

// 选择用户
const selectUserMask = ref();
// const selectUserVisible = ref(false);
const selectUserType = ref("");
const selectUser = (type: string) => {
  selectUserType.value = type;
  // selectUserVisible.value = true;
  selectUserMask.value.open();
};

const userChange = e => {
  form.technicianNo = e.userId;
  form.technicianName = e.fullName;
};

const enclosureList = ref<any[]>([]); // 附件列表

const getEnclosureList = () => {
  findAllEventAttachment({
    "eventAttachmentDto.eno": details.value.eno,
    "eventAttachmentDto.eventType": "itsm.change"
  }).then((res: any) => {
    enclosureList.value = res || [];
  });
};

import type { UploadProps } from "element-plus";
// 上传附件
const uploadChange: UploadProps["onChange"] = (uploadFile: any) => {
  loading.value = true;
  let params = new FormData();
  params.append("filedata", uploadFile.raw);
  uploadAttr("yuehaishuiwu_zhengshi", params)
    .then(res => {
      loading.value = false;
      enclosureList.value.push({
        attachmentName: uploadFile.name,
        url: res.msg,
        size: uploadFile.size
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

// 删除附件
const delFile = (item: { url: any }) => {
  ElMessageBox.confirm("确定要删除该附件？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      let index = 0;
      enclosureList.value.forEach((vo, idx) => {
        if (vo.url === item.url) {
          index = idx;
        }
      });
      enclosureList.value[index].splice(index, 1);
    })
    .catch(() => {
      // cancel operation
    });
};

const changePlanType = ref("effect");

// 定义 emit 事件
const emit = defineEmits<{
  change: [];
  add: [];
}>();

const dialogVisible = ref(false);

const addForm = ref();

// 选择服务
const selectServesMask = ref();
const showSelectServesMask = () => {
  selectServesMask.value?.open();
};

const serviceDirectoryList = ref<any[]>([]);

// 选择服务
const serveChange = list => {
  serviceDirectoryList.value = list;
};

const delServe = item => {
  let index = 0;
  serviceDirectoryList.value.forEach((element, idx) => {
    if (element.id == item.id) {
      index = idx;
    }
  });
  serviceDirectoryList.value.splice(index, 1);
};

// 选择配置项
const selectAssetMask = ref();
const showSelectAssetMask = () => {
  selectAssetMask.value?.open();
};
const assetList = ref<any[]>([]);
const assetChange = list => {
  list.forEach(data => {
    let has_item = false;
    assetList.value.forEach(item => {
      if (item.ciId == data.ciId) {
        has_item = true;
      }
    });
    // ElMessage.warning("已选择该资产，无需重复选择");
    if (!has_item) {
      assetList.value.push(data);
    }
  });
};
const delAsset = item => {
  let index = 0;
  assetList.value.forEach((element, idx) => {
    if (element.ciId == item.ciId) {
      index = idx;
    }
  });
  assetList.value.splice(index, 1);
};

const submit = async () => {
  await addForm.value.validate((valid: any, fields: any) => {
    if (valid) {
      if (!form.edesc) {
        ElMessage.warning("请输入描述");
        return false;
      }
      // 附件
      let attachmentStr = "";
      if (enclosureList.value.length > 0) {
        enclosureList.value.forEach(item => {
          attachmentStr += item.attachmentName + "==" + item.url + "==" + item.size + "-s-";
        });
      }
      // 拓展信息
      let attrValsData = ref<any>({});
      if (attrVals.value.length > 0) {
        attrVals.value.forEach(element => {
          element.children.forEach(item => {
            let key = "changeDTO.attrVals[" + item.attrName + "]";
            attrValsData.value[key] = item.value;
          });
        });
      }
      // 关联的配置项
      let ciIds = ref<any[]>([]);
      assetList.value.forEach(item => {
        ciIds.value.push("changeDTO.ciIds=" + item.ciId);
      });
      // 关联的服务
      let serviceIds = ref<any[]>([]);
      serviceDirectoryList.value.forEach(item => {
        serviceIds.value.push("changeDTO.serviceDirectoryIds=" + item.id);
      });
      // 组装数据（关联的配置项 + 关联的服务）
      let ciIdsAndServiceDirectoryIds = "";
      if (ciIds.value.length > 0 && serviceIds.value.length > 0) {
        ciIdsAndServiceDirectoryIds = ciIds.value.join("&") + "&" + serviceIds.value.join("&");
      } else if (ciIds.value.length > 0) {
        ciIdsAndServiceDirectoryIds = ciIds.value.join("&");
      } else if (serviceIds.value.length > 0) {
        ciIdsAndServiceDirectoryIds = serviceIds.value.join("&");
      }
      if (!ciIdsAndServiceDirectoryIds) {
        ciIdsAndServiceDirectoryIds = "changeDTO.ciIds=";
      }
      loading.value = true;
      if (props.type == "upgrade") {
        // 请求升级成变更
        saveChange({
          "changeDTO.creator": userStore.username,
          "changeDTO.actionName": "新增",
          "changeDTO.piv.eno": details.value.eno,
          "changeDTO.piv.etitle": details.value.etitle,
          "changeDTO.piv.eventCode": details.value.eventCode,
          "changeDTO.piv.approverNum": details.value.approverNum,
          "changeDTO.piv.approveCommentDTO": details.value.approveCommentDTO,
          "changeDTO.piv.needApprove": details.value.needApprove,
          "changeDTO.piv.approval": false,
          "changeDTO.etitle": form.etitle,
          "changeDTO.edesc": form.edesc,
          "changeDTO.companyNo": form.companyNo,
          "changeDTO.companyName": form.companyName,
          "changeDTO.categoryNo": form.categoryNo,
          "changeDTO.categoryName": form.categoryName,
          "changeDTO.planStartTime": form.planStartTime, // 计划开始时间
          "changeDTO.planEndTime": form.planEndTime, // 计划结束时间
          "changeDTO.priorityNo": form.priorityNo,
          "changeDTO.effectRangeNo": form.effectRangeNo,
          "changeDTO.seriousnessNo": form.seriousnessNo,
          "changeDTO.orgNo": form.orgNo,
          "changeDTO.technicianNo": form.technicianNo,
          "changeDTO.technicianName": form.technicianName,
          "changeDTO.attachmentStr": attachmentStr, // 附件
          "changeDTO.effect": form.effect, // 影响
          "changeDTO.onLinePlan": form.onLinePlan, // 上线计划
          "changeDTO.returnPlan": form.returnPlan, // 回退计划
          "changeDTO.checklist": form.checklist, // 测试计划
          // "changeDTO.serviceDirectoryIds": serviceIds.value,
          ...attrValsData
        })
          .then(() => {
            loading.value = false;
            ElMessage.success("保存成功");
            dialogVisible.value = false;
            emit("add");
          })
          .catch(() => {
            loading.value = false;
          });
      } else if (details.value.eno) {
        // 编辑
        changeEdit(ciIdsAndServiceDirectoryIds, {
          "changeDTO.creator": userStore.username,
          "changeDTO.actionName": "编辑",
          "changeDTO.eno": details.value.eno,
          "changeDTO.statusNo": details.value.statusNo || "",
          "changeDTO.needApprove": false,
          "changeDTO.changeNo": details.value.changeNo,
          "changeDTO.etitle": form.etitle,
          "changeDTO.edesc": form.edesc,
          "changeDTO.companyNo": form.companyNo,
          "changeDTO.companyName": form.companyName,
          "changeDTO.categoryNo": form.categoryNo,
          "changeDTO.categoryName": form.categoryName,
          "changeDTO.planStartTime": form.planStartTime, // 计划开始时间
          "changeDTO.planEndTime": form.planEndTime, // 计划结束时间
          "changeDTO.priorityNo": form.priorityNo,
          "changeDTO.effectRangeNo": form.effectRangeNo,
          "changeDTO.seriousnessNo": form.seriousnessNo,
          "changeDTO.orgNo": form.orgNo,
          "changeDTO.technicianNo": form.technicianNo,
          "changeDTO.technicianName": form.technicianName,
          "changeDTO.attachmentStr": attachmentStr, // 附件
          "changeDTO.effect": form.effect, // 影响
          "changeDTO.onLinePlan": form.onLinePlan, // 上线计划
          "changeDTO.returnPlan": form.returnPlan, // 回退计划
          "changeDTO.checklist": form.checklist, // 测试计划
          ...attrValsData
        })
          .then(() => {
            loading.value = false;
            ElMessage.success("保存成功");
            dialogVisible.value = false;
            emit("change");
          })
          .catch(() => {
            loading.value = false;
          });
      } else {
        // 新增
        statCiChangeConflict({
          "changeDTO.ciIds": ciIds.value
        })
          .then(() => {
            saveChange({
              "changeDTO.creator": userStore.username,
              "changeDTO.actionName": "新增",
              "changeDTO.piv.eno": "",
              "changeDTO.piv.etitle": "",
              "changeDTO.piv.eventCode": "",
              "changeDTO.piv.approverNum": "",
              "changeDTO.piv.approveCommentDTO": "",
              "changeDTO.piv.needApprove": "",
              "changeDTO.piv.approval": false,
              "changeDTO.etitle": form.etitle,
              "changeDTO.edesc": form.edesc,
              "changeDTO.companyNo": form.companyNo,
              "changeDTO.companyName": form.companyName,
              "changeDTO.categoryNo": form.categoryNo,
              "changeDTO.categoryName": form.categoryName,
              "changeDTO.planStartTime": form.planStartTime, // 计划开始时间
              "changeDTO.planEndTime": form.planEndTime, // 计划结束时间
              "changeDTO.priorityNo": form.priorityNo,
              "changeDTO.effectRangeNo": form.effectRangeNo,
              "changeDTO.seriousnessNo": form.seriousnessNo,
              "changeDTO.orgNo": form.orgNo,
              "changeDTO.technicianNo": form.technicianNo,
              "changeDTO.technicianName": form.technicianName,
              "changeDTO.attachmentStr": attachmentStr, // 附件
              "changeDTO.effect": form.effect, // 影响
              "changeDTO.onLinePlan": form.onLinePlan, // 上线计划
              "changeDTO.returnPlan": form.returnPlan, // 回退计划
              "changeDTO.checklist": form.checklist, // 测试计划
              // "changeDTO.serviceDirectoryIds": serviceIds.value,
              ...attrValsData
            })
              .then(() => {
                loading.value = false;
                ElMessage.success("保存成功");
                dialogVisible.value = false;
                emit("add");
              })
              .catch(() => {
                loading.value = false;
              });
          })
          .catch(() => {
            loading.value = false;
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const tabName = ref("one");
const cacheCateData = ref<any[]>([]);
const loading = ref(false);

const open = (item: any) => {
  for (const key in form) {
    if (Object.prototype.hasOwnProperty.call(form, key)) {
      form[key] = "";
    }
  }
  details.value = {};
  enclosureList.value = [];
  attrVals.value = [];
  tabName.value = "one";
  if (props.type == "upgrade") {
    // 请求升级成变更
    details.value = item;
    form.etitle = item.etitle;
    form.edesc = item.edesc;
    form.companyNo = item.companyNo;
    form.companyName = item.companyName;
    findAllEventAttachment({
      "eventAttachmentDto.eno": item.eno,
      "eventAttachmentDto.eventType": "itsm.request"
    }).then((res: any) => {
      // 附件列表
      enclosureList.value = res || [];
    });
  } else if (item) {
    // 编辑
    details.value = item;
    loading.value = true;
    assigneeGroupName.value = item.orgName;
    console.log(item);
    // 变更详情
    changeInfo({
      eno: item.eno
    })
      .then((res: any) => {
        loading.value = false;
        res.edesc = res.edesc
          .replace(
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
            ""
          )
          .trim();
        details.value = {
          ...details.value,
          ...res
        };
        for (const key in form) {
          if (Object.prototype.hasOwnProperty.call(form, key)) {
            if (res[key]) {
              form[key] = res[key];
            }
          }
        }
        form.categoryNo = res.categoryNo || "";
        // 默认显示分类
        if (form.categoryNo) {
          cacheCateData.value = [
            {
              label: res.categoryNo,
              value: res.categoryName
            }
          ];
        }
        if (res.listEvent || res.listEvent.length > 0) {
          serviceDirectoryList.value = res.listEvent.map(item => {
            return {
              id: item.eventId,
              cname: item.eventName
            };
          });
        } else {
          serviceDirectoryList.value = [];
        }
        assetList.value = res.cigDTO || [];
      })
      .catch(() => {
        loading.value = false;
      });
    getEnclosureList(); // 获取附件列表
  } else {
    // 新增
    templateJson.value = "";
    form.companyNo = userStore.userInfo.companyNo || "";
    form.companyName = userStore.userInfo.companyName || "";
    // 获取变更模板
    findByTemplateType({
      "templateDTO.templateType": "change"
    }).then((res: any) => {
      tempList.value = res || [];
    });
  }
  dialogVisible.value = true;
};

onMounted(() => {
  if (
    orgList.value.length == 0 ||
    priorityList.value.length == 0 ||
    priorityList.value.length == 0 ||
    seriousnessList.value.length == 0 ||
    effectRangeList.value.length == 0
  ) {
    allChangeOptions.getAllOptions();
  }
});

defineExpose({
  open
});
</script>

<style lang="scss" scoped></style>
